from  flask_classy import FlaskView, route

from ..schema.error import SHOP_CART_NOT_EXIST, SHOP_CART_HAS_OWNER, SHOP_CART_STATUS_ERROR
from . import current_member, require_login
from ..schema.object import success_schema, ShopCharItemSchema, currency_schema, member_summary_schema
from ..schema.param import  shop_cart_item_param, currency_param
from ..models.shop_cart import  ShopCart
from flask import request, g
from ..models.currency import Currency
from ..models.account import Account
from ..models.member import Member

class MembersView(FlaskView):
    def _get_sales_summary(self, member_id):
        # 销量
        member_info = Member.get_member(member_id)
        return {
            'total': member_info.deal_count
        }

    @route('/<member_id>/summary')
    @require_login
    def summary(self, member_id):
        member = g.member
        # 账户情况

        account = member.account

        # 评价

        return member_summary_schema.jsonify({
            'account': account,
            'sales': self._get_sales_summary(member.id)
        })

    @route('shop_cart', methods=['GET'])
    @require_login
    def get_shop_cart(self):
        member = current_member()

        params, _ = currency_param.load(request.values)

        currency = params.get('currency') or Currency.get_main_currency()

        shop_cart_items_schema = ShopCharItemSchema(many=True, context={'currency': currency})
        from ..models.shop_cart import ShopCart

        shop_cart = ShopCart.get_by_member(member)
        return success_schema.jsonify(
            {
                'currency': currency_schema.dump(currency).data,
                'cart_items': shop_cart_items_schema.dump(
                    shop_cart.items).data
            }
        )





    @route('shop_cart', methods=['POST'])
    @require_login
    def add_shop_cart(self):
        shop_cart_id = '085d0ea7-3758-4992-bc66-3f7cb1ed5465'
        from ..models.shop_cart import ShopCart

        shop_cart = ShopCart.get_or_none(ShopCart.id == shop_cart_id)

        if not shop_cart:
            return SHOP_CART_NOT_EXIST.jsonify()
        if shop_cart.member is not None:
            return SHOP_CART_HAS_OWNER.jsonify()
        if not shop_cart.is_normal:
            return SHOP_CART_STATUS_ERROR.jsonify()
        shop_cart.member = current_member()

        shop_cart.save()
        return success_schema.jsonify()
